<!--通用自定义流程提交按钮-->
<style lang="less">
</style>
<template>
    <span>
      <a-button :type="btnType" style="padding: 0 5px !important;" @click="applySubmit()" :loading="submitLoading"
      >{{ text }}</a-button>
      <!--当前节点是驳回或退回的第一个发起人节点,重新发起弹窗-->
      <a-modal :z-index="100" :title="firstInitiatorTitle" @cancel="firstInitiatorOpen = false"
               :visible.sync="firstInitiatorOpen"
               :width="'50%'" append-to-body
      >
         <a-descriptions bordered layout="vertical">
           <a-descriptions-item :span="3">
                 <a-badge status="processing" text="选择提醒"/>
            </a-descriptions-item>
            <a-descriptions-item label="重新发起新流程按钮"
                                 labelStyle="{ color: '#fff', fontWeight: 'bold', fontSize='18px'}"
            >
              重新发起新流程会删除之前发起的任务,重新开始.
            </a-descriptions-item>
            <a-descriptions-item label="继续发起老流程按钮">
              继续发起流程就在原来流程基础上继续流转.
            </a-descriptions-item>
         </a-descriptions>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="reStartByDataId(true)">重新发起新流程</el-button>
          <el-button type="primary" @click="reStartByDataId(false)">继续发起老流程</el-button>
          <el-button @click="firstInitiatorOpen = false">取 消</el-button>
        </span>
      </a-modal>
      <!--选择自定义业务单-->
      <a-modal @cancel="flowOpen = false" :title="flowTitle" :visible.sync="flowOpen" width="70%" append-to-body>
        <el-row :gutter="64">
          <el-col :span="20" :xs="64" style="width: 100%">
            <el-table ref="singleTable" :data="processList" border highlight-current-row style="width: 100%">
               <el-table-column type="selection" width="55" align="center"/>
               <el-table-column label="主键" align="center" prop="id" v-if="true"/>
               <el-table-column label="业务表单名称" align="center" prop="businessName"/>
               <el-table-column label="业务服务名称" align="center" prop="businessService"/>
               <el-table-column label="流程名称" align="center" prop="flowName"/>
               <el-table-column label="关联流程发布主键" align="center" prop="deployId"/>
               <el-table-column label="前端路由地址" align="center" prop="routeName"/>
               <el-table-column label="组件注入方法" align="center" prop="component"/>
               <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                 <template slot-scope="scope">
                   <el-button size="mini" type="text" @click="selectForm(scope.row)">确定</el-button>
                 </template>
               </el-table-column>
              </el-table>
          </el-col>
        </el-row>
      </a-modal>
      <!--选择指定用户弹窗-->
      <el-dialog :title="userData.title" :visible.sync="userData.open" width="60%" append-to-body>
        <el-row type="flex" :gutter="20">
          <!--部门数据-->
          <el-col :span="5">
            <el-card shadow="never" style="height: 100%">
              <div slot="header">
                <span>部门列表</span>
              </div>
              <div class="head-container">
                <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search"/>
                <el-tree
                  :data="deptOptions"
                  :props="deptProps"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  ref="tree"
                  default-expand-all
                  @node-click="handleNodeClick"
                />
              </div>
            </el-card>
          </el-col>
          <el-col :span="18">
            <el-table ref="userTable"
                      :key="userData.type"
                      height="500"
                      v-loading="userLoading"
                      :data="userList"
                      highlight-current-row
                      @current-change="changeCurrentUser"
                      @selection-change="handleSelectionChange">
              <el-table-column v-if="userData.type === 'copy' || userData.type === 'next' || userData.type === 'addSign' || userData.type === 'approval'" width="55" type="selection" />
              <el-table-column v-else width="30">
                <template slot-scope="scope">
                  <el-radio :label="scope.row.userId" v-model="currentUserId">{{''}}</el-radio>
                </template>
              </el-table-column>
              <el-table-column label="用户名" align="center" prop="nickName" />
              <el-table-column label="手机" align="center" prop="phoneNumber" />
              <el-table-column label="部门" align="center" prop="dept.deptName" />
            </el-table>
            <pagination
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </el-row>
        <span slot="footer" class="dialog-footer">
          <el-button @click="userData.open = false">取 消</el-button>
          <el-button type="primary" @click="submitUserData">确 定</el-button>
        </span>
      </el-dialog>
    </span>
</template>

<script>
import { deleteActivityAndJoin, getProcess, isFirstInitiator, startByDataId } from '@/api/workflow/process'
import { deptTreeSelect, selectUser } from '@/api/system/user'
import { complete } from '@/api/workflow/task'

export default {
  name: 'ActApplyBtn',
  components: {},
  props: {
    btnType: {
      type: String,
      default: 'link',
      required: false
    },
    /**
     * 业务表id
     */
    dataId: {
      type: String,
      default: '',
      required: true
    },
    serviceName: {
      type: String,
      default: '',
      required: true
    },
    variables: {
      type: Object,
      default: {}
    },
    text: {
      type: String,
      default: '提交流程',
      required: false
    }
  },
  data() {
    return {
      modalVisible: false,
      submitLoading: false,
      form: {},
      //第一个发起人重新发起弹窗开关
      firstInitiatorOpen: false,
      firstInitiatorTitle: '',
      //自定义业务单数据
      processList: [],
      //自定义表单弹窗开关
      flowOpen: false,
      flowTitle: '',
      //选择的自定义业务单ID
      customFromId: '',
      /*---------------用户选择弹窗数据--------------------- */
      //用户选择弹窗数据
      userData: {
        title: '',
        type: '',
        open: false,
      },
      userLoading: false,
      //用户表格数据
      userList: null,
      currentUserId: null,
      //查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        userIds:null
      },
      total: 0,
      userMultipleSelection: [],
      taskForm:{
        dataId:"",//自定义业务ID
        comment:"", // 意见内容
        procInsId: "", // 流程实例编号
        taskId: "" ,// 流程任务编号
        copyUserIds: "", // 抄送人Id
        vars: "",
        targetKey:""
      },
      //部门名称
      deptName: undefined,
      //部门树选项
      deptOptions: undefined,
      deptProps: {
        children: "children",
        label: "label"
      },
    }
  },
  created() {
  },
  watch: {},
  methods: {
    /**
     * 选择自定义业务单
     * @param row
     */
    selectForm(row) {
      this.customFromId = row.id
      this.flowOpen = false
      let params = Object.assign({
        dataId: this.dataId
      }, this.variables)
      startByDataId(this.dataId, this.customFromId, this.serviceName, params).then(res => {
        if(res.code === 200 && res.data &&res.data.hasOwnProperty('nextApproval') && res.data.nextApproval === '${approval}') {
          this.taskForm.variables = res.data.variables;
          this.taskForm.taskId = res.data.taskId;
          this.taskForm.procInsId = res.data.procInsId;
          this.onSelectNextApprovals();
        } else {
          this.$message.success(res.msg)
          this.$emit('success')
        }
      }).finally(() => (this.submitLoading = false))
    },
    /**
     * 重新发起新流程/继续发起老流程
     * @param isNewFlow
     */
    reStartByDataId(isNewFlow) {
      if (isNewFlow) {
        this.submitLoading = true
        deleteActivityAndJoin(this.dataId, this.variables).then(res => {
          if (res.code == 200 && res.data) {
            //若删除成功
            let params = Object.assign({
              dataId: this.dataId
            }, this.variables)
            startByDataId(this.dataId, this.customFromId, this.serviceName, params).then(res => {
              this.firstInitiatorOpen = false
              if(res.code === 200 && res.data &&res.data.hasOwnProperty('nextApproval') && res.data.nextApproval === '${approval}') {
                this.taskForm.variables = res.data.variables;
                this.taskForm.taskId = res.data.taskId;
                this.taskForm.procInsId = res.data.procInsId;
                this.onSelectNextApprovals();
              } else {
                this.$message.success(res.msg)
                this.$emit('success')
              }
            })
          }
        }).finally(() => (this.submitLoading = false))
      } else {
        //继续原有流程流转，跳到流程处理界面上
        //console.log("this.variables",this.variables);
        this.$router.push({
          path: '/flowable/task/record/index',
          query: {
            procInsId: this.variables.processInstanceId,
            deployId: this.variables.deployId,
            taskId: this.variables.taskId,
            businessKey: this.dataId,
            nodeType: '',
            category: 'zdyyw',
            finished: true
          }
        })
      }
    },
    /**
     * 提交流程申请
     */
    async applySubmit() {
      if (this.dataId && this.dataId.length < 1) {
        this.error = '必须传入参数dataId'
        this.$message.error(this.error)
        return
      }
      if (this.serviceName && this.serviceName.length < 1) {
        this.error = '必须传入参数serviceName'
        this.$message.error(this.error)
        return
      } else {
        this.error = ''
      }
      //对于自定义业务,判断是否是驳回或退回的第一个发起人节点
      this.showLoading()
      let res1
      await isFirstInitiator(this.dataId, this.variables).then(res => {
        res1=res
      }).catch(() => (this.hideLoading()))
      if (res1.code === 200 && res1.data) {
        //若是，弹出窗口选择重新发起新流程还是继续老流程
        this.firstInitiatorTitle = '根据自己需要进行选择'
        this.firstInitiatorOpen = true
      }else {
        const processParams = {
          serviceName: this.serviceName
        }
        //查询关联流程信息
        let res2
        await getProcess(processParams).then(res => {
          res2=res
        }).catch(() => (this.hideLoading()))
        this.processList = res2.data
        if (this.processList && this.processList.length > 1) {
          this.flowOpen = true
        }else if (this.processList && this.processList.length === 1) {
          this.customFromId = res2.data[0].id
          let params = Object.assign({
            dataId: this.dataId
          }, this.variables)
          //启动流程
          await startByDataId(this.dataId, this.customFromId, this.serviceName, params).then(res => {
            console.log('startByDataId res', res)
            if(res.code === 200 && res.data &&res.data.hasOwnProperty('nextApproval') && res.data.nextApproval === '${approval}') {
              this.taskForm.dataId = res.data.dataId;
              this.taskForm.variables = res.data.variables;
              this.taskForm.taskId = res.data.taskId;
              this.taskForm.procInsId = res.data.procInsId;
              if(res.data.candidateUsers){
                this.queryParams.userIds=res.data.candidateUsers.join(",")
              }
              this.onSelectNextApprovals();
            } else {
              this.$message.success(res.msg)
              this.$emit('success')
            }
          }).catch(() => (this.hideLoading()))
        } else {
          this.$message.error('检查该业务是否已经关联流程！')
        }
      }
      this.hideLoading()
    },
    /**
     * 显示加载中
     */
    showLoading(){
      this.submitLoading = true
      this.$emit("showLoading")
    },
    /**
     * 关闭加载中
     */
    hideLoading(){
      this.submitLoading = false
      this.$emit("hideLoading")
    },
    onSelectNextApprovals() {
      this.userMultipleSelection = this.nextApproval;
      this.onSelectUsers('指定接收人', 'approval')
    },
    onSelectUsers(title, type) {
      this.userData.title = title;
      this.userData.type = type;
      this.getTreeSelect();
      this.getList()
      this.userData.open = true;
    },
    /**
     * 查询部门下拉树结构
     */
    getTreeSelect() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /**
     * 查询用户列表
     */
    getList() {
      this.userLoading = true;
      selectUser(this.$addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.toggleSelection(this.userMultipleSelection);
        this.userLoading = false;
      });
    },
    /**
     * 筛选节点
     * @param value
     * @param data
     * @returns {boolean}
     */
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /**
     * 节点单击事件
     * @param data
     */
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    /**
     * 切换选择用户
     * @param selection
     */
    toggleSelection(selection) {
      if (selection && selection.length > 0) {
        this.$nextTick(()=> {
          selection.forEach(item => {
            let row = this.userList.find(k => k.userId === item.userId);
            this.$refs.userTable.toggleRowSelection(row);
          })
        })
      } else {
        this.$nextTick(() => {
          this.$refs.userTable.clearSelection();
        });
      }
    },
    /**
     * 多选框选中数据
     * @param selection
     */
    handleSelectionChange(selection) {
      this.userMultipleSelection = selection
    },
    /**
     * 选择用户
     * @param val
     */
    changeCurrentUser(val) {
      this.currentUserId = val.userId
    },
    /**
     * 选择用户确定
     * @returns {boolean}
     */
    submitUserData() {
      let type = this.userData.type;
      if (type === 'approval' ) {
        if (!this.userMultipleSelection || this.userMultipleSelection.length <= 0) {
          this.$modal.msgError("请选择用户");
          return false;
        }
        if (this.userMultipleSelection.length > 1) {
          this.$modal.msgError("只能选择一个用户");
          return false;
        }
        let userIds = this.userMultipleSelection.map(k => k.userId);
        if (type === 'approval') {
          // 设置下一级接收人userName信息
          this.nextApproval = this.userMultipleSelection;
          this.taskForm.nextApproval = userIds instanceof Array ? userIds.join(',') : userIds;
        }
        this.userData.open = false;
        console.log("submitUserData type",type);
        if (type === 'approval') {
          this.taskForm.comment = "发起人自动审批";
          console.log("submitUserData taskForm",this.taskForm);
          complete(this.taskForm).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.$emit('success')
          });
        }
      } else {
        if (!this.taskForm.comment) {
          this.$modal.msgError("请输入审批意见");
          return false;
        }
        if (!this.currentUserId) {
          this.$modal.msgError("请选择用户");
          return false;
        }
        this.taskForm.userId = this.currentUserId;
      }

    },
  }
}
</script>
